var saisiePageLoaded = true;
var currentPage = 'saisie';
var user = {};
var batterieTypeTemplate = '<option></option>';
var batteries = null;
var hashFunctions = {
	menus: "displayMenuManagement",
	batteries: "displayBatteriesManagement",
	'new-batterie': "newBatterie",
	batterie: "displayBatterieForm"
};

/**
 * initialization
 */
$.ajax({
	type: 'GET',
	url: serverPath + '/front/saisie/',
	success: function(userData) {
		user = userData;
		
		window.onhashchange = hashChange;

		loadBatteries(function(){
			hashChange();
		});
	},
	error: function(data) {
		window.location = indexPagePath;
	},
	dataType: 'json'
});

function loadPanel(tag, param) {
	param = (param === undefined) ? "" : "_" + param; 
	location.hash = tag + param;
}

function hashChange() {
	var hash = location.hash;
	hash = (hash.indexOf("#") == 0) ? hash.substring(1) : hash;
	
	var arguments = hash.split ("_");
	
	try {
		window[hashFunctions[arguments[0]]](arguments[1]);
	}catch(e) {
		// not recognized tag
		displaySaisie();
	}	
}

function loadBatteries(callback) {
	$.getJSON(serverPath + '/batterie/list?w=1', function(data) {
		batteries = data.batteries;
		if (typeof callback !== 'undefined') {
			callback();
		}
	});
}

function displaySaisie() {
	hideContainers();
	document.location.hash="main";
	showContainer('menuContainer');
}

/*
 * Actions 
 */

function back() {
	if (!$('.menuContainer').hasClass('hidden')) {
		displayMainMenu();
	}else if (!$('.batteriesManagement').hasClass('hidden')) {
		displaySaisie();
	}else if (!$('.batterieForm').hasClass('hidden')) {
		loadPanel('batteries');
	}else if (!$('.newBatterieForm').hasClass('hidden')) {
		loadPanel('batteries');
	}else if (!$('.menuManagement').hasClass('hidden')) {
		displaySaisie();
	}else {
		displayMainMenu();
	}
}
